package mvp.cklm.testtask.util;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Properties;

/**
 * Created with IntelliJ IDEA.
 * User: valera
 * Date: 25.02.14
 * Time: 8:33
 */
public class ConfigKeeper {
    private static final Logger log = LoggerFactory.getLogger(ConfigKeeper.class);
    private static MongoClient client;
    private static String dbName;

    public ConfigKeeper(String path) throws UnknownHostException {
        initConnection(path);
    }

    public static MongoClient getClient() {
        return client;
    }

    public static String getDbName() {
        return dbName;
    }

    public static void initConnection(String path) throws UnknownHostException {
        if (client == null) {
            Properties props = getProperties(path);
            String servers = props.getProperty("servers");
            client = new MongoClient(new MongoClientURI(servers));
            dbName = props.getProperty("db");
        }
    }

    private static Properties getProperties(String path) {
        Properties db_prop = new Properties();
        try {
            db_prop.load(new FileInputStream(path));
        } catch (Exception e) {
            log.error("getProperties{}", e);
        }
        return db_prop;
    }
}
